#include "QtImageDialog.h"
#include "QtBox2DView.h"
#include "QtBox2dAbstractItem.h"
#include "QtBox2DScene.h"

#include <QtGui/QtGui>

QtImageDialog::QtImageDialog(QWidget* parent /* = 0 */, Qt::WindowFlags wFlag /* = 0 */)
	: QDialog(parent), mImageWidget(0)
{
	mImageWidget = new QtImageList(this);

	setWindowTitle("Image Dialog");
	QVBoxLayout* layout = new QVBoxLayout(this);
	layout->addWidget(mImageWidget);

	QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
	layout->addWidget(buttonBox);
	buttonBox->setCenterButtons(true);

	setLayout(layout);

	connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
	connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
}

QtImageDialog::~QtImageDialog()
{

}

void QtImageDialog::initIcons()
{
	QtBox2DView* view = dynamic_cast<QtBox2DView*>(parent());
	if (!view)
	{
		return;
	}

	QtBox2DScene* b2Scene = dynamic_cast<QtBox2DScene*>(view->scene());

	const QMap<QString, QImage*>& images = b2Scene->getImages();

	QMap<QString, QImage*>::const_iterator itor= images.constBegin();
	
	for (;itor != images.constEnd(); ++itor)
	{
		QImage* image = itor.value();
		if (image != 0)
		{
			QPixmap pixmap(64,64);
			pixmap.convertFromImage(*image);
			mImageWidget->addImage(*image, itor.key());
		}
	}
}

void QtImageDialog::accept()
{
	QtBox2DView* view = static_cast<QtBox2DView*>(parentWidget());

	QList<QListWidgetItem*> imageItems = mImageWidget->selectedItems();
	if (view && imageItems.size() > 0)
	{
		QList<QGraphicsItem*> items = view->scene()->selectedItems();
		QGraphicsItem* item = 0 ;
		foreach(item, items)
		{
			QtBox2DAbstractItem* pItem = dynamic_cast<QtBox2DAbstractItem*>(item);
			if (pItem)
			{
				QtBox2DScene* b2Scene = dynamic_cast<QtBox2DScene*>(pItem->scene());
				b2Scene->pushUndoNormal(b2Scene->getSelectedNames(), "mTexName", pItem->texName());
				pItem->setTexName(imageItems.at(0)->data(Qt::UserRole).toString());
				b2Scene->pushRedoNormal("mTexName", pItem->texName());

				pItem->update();
			}
		}
	}
        QDialog::accept();
}
